package main

import (
	"context"
	"log"

	pb "gitee.com/whello/shippy-consignment/proto/consignment"
	vesselPb "gitee.com/whello/shippy-vessel/proto/vessel"
	"gopkg.in/mgo.v2"
)

type service struct {
	session      *mgo.Session
	vesselClient vesselPb.VesselServiceClient
}


func (s *service) GetRepo() Repository {
	return &ConsignmentRepository{s.session.Clone()}
}

func (s *service) CreateConsignment(ctx context.Context, req *pb.Consignment, resp *pb.Response) error {
	defer s.GetRepo().Close()

	vReq := &vesselPb.Specification{
		Capacity:  int32(len(req.Containers)),
		MaxWeight: req.Weight,
	}

	vResp, err := s.vesselClient.FindAvailble(context.Background(), vReq)
	if err != nil {
		return err
	}

	log.Printf("found vessel: %s\n", vResp.Vessel.Name)
	req.VesselId = vResp.Vessel.Id

	err = s.GetRepo().Create(req)
	if err != nil {
		return err
	}
	resp.Created = true
	resp.Consignment = req
	return nil
}

func (s *service) GetConsignments(ctx context.Context, req *pb.GetRequest, resp *pb.Response) error {
	defer s.GetRepo().Close()

	consignments, err := s.GetRepo().GetAll()
	if err != nil {
		return err
	}
	resp.Consignments = consignments

	return nil
}
